package cn.mesmile.amqp.demo.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author zb
 * @date 2021/3/14 23:02
 * @Description:
 */
public class Send {

    private final static String EXCHANGE_NAME = "exchange_topic";

    /**
     * 当交换器类型为 fanout 的时候，在绑定队列的时候 Routing key 选填
     */
    public static void main(String[] argv) throws Exception {


        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("39.105.17.127");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setPort(5672);
        factory.setVirtualHost("/dev");


        //JDK7语法 或自动关闭 connnection和channel
        try (Connection connection = factory.newConnection();

             Channel channel = connection.createChannel()) {

            // 声明交换机
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

            String user = "这是用户user相关";
            String order = "这是订单order相关";
            String error = "这是错误error相关";

            // 发送消息
            channel.basicPublish(EXCHANGE_NAME, "user.log.info", null, user.getBytes(StandardCharsets.UTF_8));
            channel.basicPublish(EXCHANGE_NAME, "order.log.info", null, order.getBytes(StandardCharsets.UTF_8));
            channel.basicPublish(EXCHANGE_NAME, "error.log.info", null, error.getBytes(StandardCharsets.UTF_8));

            System.out.println(">>>>>>>>>>>> 发送消息成功！");
        }

    }
}
